<template>
  <div class="login">
    <div v-if="isMobile" class="smallLogo"><img src="../../assets/front-img/logo.png" alt=""></div>
    <Top v-else @showRegister="showRegister" @showLogin="showLogin"/>
    <div class="container-back">
      <div class="login-container">
        <div class="bigLogo"></div>
        <Register
          v-if="showReg === 1"
          @showLogin="showLogin"
          :isComponent="true"
        />
        <ForgetPassword v-else-if="showReg === 2" @showLogin="showLogin" />
				<MobileLogin  v-else-if="showReg===3" @showLogin="showLogin"/>
        <el-form
          ref="loginForm"
          v-else
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title">账户登录</h3>
          </div>
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model.trim="loginForm.username"
              placeholder="请输入登录账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password">
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入8位以上字母和数字组合密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-tooltip>
          <el-form-item label="账户身份" prop="type">
            <el-radio-group v-model="loginForm.type">
              <el-radio
                v-for="item in typeJson"
                :key="item.value"
                :label="item.value"
              >{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-button
            :loading="loading"
            type="primary"
            class="loginBt"
            @click.native.prevent="handleLogin"
          >登录</el-button>
          <div class="toReg">
            <span @click="showForget">忘记密码？</span>
           <div style="display: flex;justify-content: center;align-items: center;">
						  <span @click="showMobileLogin">手机号登录</span>|
           	 <span @click="showRegister">免费注册></span>
           </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapActions } from "vuex";
// import SocialSign from './components/SocialSignin'
import Register from "@/components/Register";
import ForgetPassword from "@/components/ForgetPassword";
import Top from "@/views/front/components/Top";
import MobileLogin from "./components/MobileLogin.vue";
import {MemberEasemob} from "@/api/user";


export default {
  name: "Login",
  components: {
    //  SocialSign,
    Register,
    ForgetPassword,
    Top,
		MobileLogin
  },
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
        type: 2
      },
      typeJson: Object.assign({}, this.$store.state.user.typeJson),
      loginRules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [
          {
            required: true,
            validator: this.$passwordValidator,
            trigger: "blur"
          }
        ]
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      showReg: 0,
      isMobile: false
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    if (this.$route.query.recommend) {
      this.showRegister();
    }
    this.updateIsMobile();
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
		// 从其他页面进入注册
		if(this.$route.query.type==1){
			this.showRegister();
		}
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    } 
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    ...mapActions(["onLogin", "setRegisterFlag", "onRegister"]),
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(response => {
              this.$store.dispatch("user/getInfo", true).then(res => {

                this.loading = false;
                if (res.status !== 1) {
                  const isFront = this.$route.query.redirect.includes("/front");
                  if (!isFront) {
                    // const message = this.returnMessage(res.status);
                    // this.$alert(message, {
                    //   confirmButtonText: "确定",
                    //   callback: action => {}
                    // });
                    this.$store.commit("setReloadLeftMenu", true)
                    this.$router.push({
                      path: "/profile/index"
                    });
                  } else {
                    this.$store.commit("setReloadLeftMenu", true)
                    this.$router.push({
                      // path: this.redirect || "/front-home",
                      path: "/profile/index"
                      // query: this.otherQuery
                    });
                  }
                } else {

                  //判断是否注册环信
                  if(res.easemobStatus === 0){
                    // 注册
                    this.onRegister({
                    	username: res.mobile.toLowerCase(),
                    	password: res.mobile,
                    	nickname: res.name||'',
                    });
                    MemberEasemob().then(res=>{
                      console.log(res);
                    }).catch(err=>{
                      console.log(err);
                    })
                    setTimeout(()=>{
                      this.onLogin({
                      	username: res.mobile.toLowerCase(),
                      	password: res.mobile
                      });
                    },500)
                  } else if(res.easemobStatus === 1){
                    this.onLogin({
                    	username: res.mobile.toLowerCase(),
                    	password: res.mobile
                    });
                  }
                  this.$store.commit("setReloadLeftMenu", true)
                  this.$router.push({
                    // path: this.redirect || "/front-home",
                    
                    path: "/profile/index"
                    // query: this.otherQuery
                  });
                }
              });
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    returnMessage(status) {
      let text = "";
      switch (status) {
        case 0:
          text = "企业认证信息已失效，请重新认证";
          break;
        case 2:
          text = "请完善企业认证信息";
          break;
        case 3:
          text = "企业认证中，请耐心等待";
          break;

        default:
          text = "请完善企业认证信息";
          break;
      }
      return text;
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    showRegister() {
      this.showReg = 1;
    },
    showForget() {
      this.showReg = 2;
    },
    showLogin() {
      this.showReg = 0;
    },
		showMobileLogin(){
			 this.showReg = 3;
		},

    updateIsMobile() {
      let screenWidth = document.body.clientWidth;
      this.isMobile = screenWidth < 750 ? true : false;
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
};
</script>
<style scoped>
  /deep/.svg-icon{
    color: #666666;
  }
</style>
<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #fff;
$light_gray: #000;
$cursor: #000;
$them: #965f29;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-select {
    width: calc(100% - 30px);
    .el-input {
      width: 100%;
    }
  }
  .el-input {
    display: inline-block;
    height: 53px;

    input {
      // background: transparent;
      border: 1px solid #e1e1e1;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 53px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px rgba(0, 0, 0, 0.1) inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
    .el-radio__input.is-checked {
      .el-radio__inner {
        border-color: $them;
        background: $them;
      }
    }
    .el-radio__input.is-checked + .el-radio__label {
      color: $them;
    }
  }
  .loginBt {
    width: 100%;
    margin: 5px 0 20px;
    padding: 20px 0;
    font-size: 18px;
    background: $them;
    border-radius: 5px;
    border: 0;

    @media only screen and (max-width: 750px) {
      margin: 0;
      padding: 10px 0px 10px;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg: #f6f6f6;
$dark_gray: #fff;
// $dark_gray: #889aa4;
$light_gray: #000;
.login {
  min-height: 100%;
  overflow: hidden;
  width: 100%;
  background-color: $bg;
  display: flex;
  flex-direction: column;
}

.smallLogo {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 38px;
  background: white;
  padding: 2px;
   img {
     height: 100%;
   }
}

.container-back {
  flex: 1;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-color: cornflowerblue;
}
.toReg {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #000;
  margin-top: 10px;
  span {
    cursor: pointer;
  }
}
.login-container {
  width: 61.8%;
  margin: 140px auto 40px;
  display: flex;
  justify-content: space-between;

  @media only screen and (max-width: 750px) {
    position: absolute;
    display: flex;
    justify-content: center;
    width: 100%;
    margin: 0;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .bigLogo {
    flex: 1;
    background: #efefef url(../../assets/front-img/logo.png) center center
      no-repeat;
    background-size: 80%;

    @media only screen and (max-width: 750px) {
      display: none;
    }
  }
  .login-form {
    width: 47%;
    position: relative;
    padding: 32px 58px 47px;
    overflow: hidden;
    background: #fff;

    @media only screen and (max-width: 750px) {
      width: 90%;
      padding: 10px;
      border-radius: 10px;
    }
  }

  .tips {
    font-size: 14px;
    color: $dark_gray;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    .title {
      font-size: 25px;
      color: $light_gray;
      margin: 15px auto 30px auto;
      font-weight: 400;

      @media only screen and (max-width: 750px) {
        font-size: 16px;
        margin: 0px auto 10px auto;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;

  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
